const express = require('express');
const router = express.Router();
const { authMiddleware, adminMiddleware } = require('../middleware/auth');
const { pool } = require('../config/db');

// 获取仪表盘统计数据
// GET /api/admin/stats
router.get('/stats', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    // 获取宠物总数
    const [petCountResult] = await pool.query('SELECT COUNT(*) as count FROM pets');
    const totalPets = petCountResult[0].count;
    
    // 获取用户总数
    const [userCountResult] = await pool.query('SELECT COUNT(*) as count FROM users');
    const totalUsers = userCountResult[0].count;
    
    // 获取待处理申请数量
    const [pendingResult] = await pool.query('SELECT COUNT(*) as count FROM adoption_applications WHERE status = "pending"');
    const pendingApplications = pendingResult[0].count;
    
    // 获取成功领养数量
    const [approvedResult] = await pool.query('SELECT COUNT(*) as count FROM adoption_applications WHERE status = "approved"');
    const successfulAdoptions = approvedResult[0].count;
    
    // 获取宠物类别分布
    const [categories] = await pool.query('SELECT * FROM categories');
    const petCategories = await Promise.all(
      categories.map(async (category) => {
        const [countResult] = await pool.query(
          'SELECT COUNT(*) as count FROM pets WHERE category_id = ?', 
          [category.id]
        );
        return {
          name: category.name,
          count: countResult[0].count
        };
      })
    );
    
    // 获取申请趋势（最近30天）
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().substring(0, 10);
    
    const [recentApplications] = await pool.query(
      `SELECT aa.*, p.name as pet_name, p.image_url as pet_image 
       FROM adoption_applications aa
       JOIN pets p ON aa.pet_id = p.id
       WHERE aa.application_date >= ?
       ORDER BY aa.application_date DESC`,
      [thirtyDaysAgoStr]
    );
    
    // 按日期分组统计申请数量
    const applicationsByDate = {};
    const dates = [];
    const counts = [];
    
    // 初始化过去30天的日期
    for (let i = 29; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateString = `${date.getMonth() + 1}/${date.getDate()}`;
      dates.push(dateString);
      applicationsByDate[dateString] = 0;
    }
    
    // 统计每天的申请数量
    recentApplications.forEach(application => {
      const date = new Date(application.application_date);
      const dateString = `${date.getMonth() + 1}/${date.getDate()}`;
      if (applicationsByDate[dateString] !== undefined) {
        applicationsByDate[dateString]++;
      }
    });
    
    // 转换为数组
    dates.forEach(date => {
      counts.push(applicationsByDate[date] || 0);
    });
    
    // 获取最近的5个申请
    const [latestApplications] = await pool.query(
      `SELECT aa.*, p.name as pet_name, p.image_url as pet_image, u.username, u.full_name, u.email
       FROM adoption_applications aa
       JOIN pets p ON aa.pet_id = p.id
       JOIN users u ON aa.user_id = u.id
       ORDER BY aa.application_date DESC
       LIMIT 5`
    );
    
    // 转换最近申请为前端所需格式
    const formattedApplications = latestApplications.map(app => ({
      id: app.id,
      user_name: app.full_name || app.username || '未知',
      pet_name: app.pet_name || '未知',
      created_at: app.application_date,
      status: app.status
    }));
    
    // 获取待处理任务（目前仅包含待处理申请）
    const [pendingTasks] = await pool.query(
      `SELECT aa.id, u.full_name, u.username
       FROM adoption_applications aa
       JOIN users u ON aa.user_id = u.id
       WHERE aa.status = 'pending'
       ORDER BY aa.application_date DESC
       LIMIT 3`
    );
    
    const formattedTasks = pendingTasks.map(app => ({
      id: app.id,
      category: 'application',
      text: `${app.full_name || app.username || '用户'}的领养申请`,
      tag: '待审核',
      tagType: 'warning',
      link: `/admin/applications?id=${app.id}`
    }));
    
    // 返回统计数据
    res.json({
      totalPets,
      totalUsers,
      pendingApplications,
      successfulAdoptions,
      petCategories,
      applicationTrend: {
        dates,
        counts
      },
      recentApplications: formattedApplications,
      pendingTasks: formattedTasks
    });
  } catch (error) {
    console.error('获取统计数据失败:', error);
    res.status(500).json({ message: '获取统计数据失败', error: error.message });
  }
});

module.exports = router; 